package br.com.lambdacore.ui.stripes;

import java.util.Arrays;
import java.util.LinkedList;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.NameBasedActionResolver;
import net.sourceforge.stripes.controller.StripesFilter;

import org.apache.commons.lang.StringUtils;

public abstract class BaseActionBean implements ActionBean {

	private BaseActionBeanContext actionBeanContext;

	public BaseActionBeanContext getContext() {
		return this.actionBeanContext;
	}

	public void setContext(ActionBeanContext actionBeanContext) {
		this.actionBeanContext = (BaseActionBeanContext) actionBeanContext;
	}

	@DefaultHandler
	public Resolution view() {
		this.prepareView();
		String jsp = this.getJsp(this.getClass());
		return new ForwardResolution("/WEB-INF/jsp/" + jsp);
	}

	protected void prepareView() {
	}

	private String getJsp(Class<? extends BaseActionBean> clazz) {
		String jsp = clazz.getName();

		jsp = this.getProcessedJspPath(jsp);

		LinkedList<String> jspSplited = new LinkedList<String>(Arrays
				.asList(StringUtils.split(jsp, '.')));

		String jspName = jspSplited.removeLast();
		jspName = this.processJspName(jspName);
		jspSplited.addLast(jspName);
		jsp = StringUtils.join(jspSplited, '/');

		return jsp + ".jsp";
	}

	private String getProcessedJspPath(String jsp) {
		String packagesConfig = StripesFilter.getConfiguration()
				.getBootstrapPropertyResolver().getProperty(
						"ActionResolver.Packages");
		String[] packages = packagesConfig.split(",");

		for (String packagez : packages) {
			if (jsp.contains(packagez)) {
				jsp = StringUtils.removeStart(jsp, packagez);
			}
		}
		return jsp;
	}

	private String processJspName(String jspName) {
		jspName = StringUtils.uncapitalize(jspName);
		for (String suffixes : NameBasedActionResolver.DEFAULT_ACTION_BEAN_SUFFIXES) {
			jspName = StringUtils.removeEnd(jspName, suffixes);
		}
		return jspName;
	}
}
